package com.zifeng.utils;

import com.zifeng.constant.RedisConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.zifeng.constant.RedisConstants.LOGIN_TOKEN_KEY;

//aop中的advice
// 该拦截器拦截所有路径
//该拦截器只做token的刷新，不做请求的实际拦截功能
@Slf4j
@Component
public class RefreshTokenUtil {

    @Resource
    private RedisUtils redisUtils;

    public boolean refreshToken(ServerHttpRequest request) {

        log.info(">>>>>>>>>>路由 拦截器刷新");
        HttpHeaders headers = request.getHeaders();
        List<String> tokenList = headers.get("token");
        if (tokenList == null || tokenList.size() == 0) return true;
        //1.获取请求头中的token
        String token = tokenList.get(0);
        if (StringUtils.isEmpty(token) || token.equals("undefined")) {
            return true;
        }

        //2.刷新token有效期
        redisUtils.expire(LOGIN_TOKEN_KEY, RedisConstants.TOKEN_TTL, TimeUnit.SECONDS);

        //3.放行
        return true;
    }
}
